import * as echarts from '../../ec-canvas/echarts';
const util = require('../../utils/util.js')
var dateTimePicker = require('../../utils/dateTimePicker.js');

const app = getApp()
const option = {
  backgroundColor: "#11274b",
  color: ["#37A2DA", "#32C5E9", "#67E0E3","#9ffcfe",'#5cc4fa'],
  series: [{
    label: {
      normal: {
        fontSize: 14
      }
    },
    type: 'pie',
    center: ['50%', '50%'],
    radius: ['40%', '60%'],
    data: [{
      value: 50,
      name: '深睡'
    }, {
      value: 20,
      name: '浅睡'
    }, {
      value: 10,
      name: '睡醒'
    }, {
      value: 10,
      name: '离床'
    }, {
      value: 10,
      name: '在床'
    }]
  }]
};

function initChart(canvas, width, height, dpr) {
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr    //new
    });

    canvas.setChart(chart);
    
    // console.log("==========",option,app.globalData.deviceId)
    // 请求接口数据
    wx.request({
      url: 'https://www.renbojiaoyu.cn/rbjk/weixin/getUserDeviceCode',
      data:{},
      method:'GET',
      header:{
        token:app.globalData.token
      },
      success:function(res){
        if(res.data.code == 500){
          wx.showModal({
            title:'提示',
            content:res.data.msg+'请绑定设备',
            showCancel:false,
            success(r){
              if(r.confirm){
                // 确定
                // that.selectComponent("#monitor").clear();
                that.setData({
                    currentTab: "0"
                })
              }else if(r.cancel){
                // 取消
              }
            }
          })
        }else if(res.data.code == 0){
          app.globalData.deviceId = res.data.deviceCode;

          wx.request({
            url: 'https://www.renbojiaoyu.cn/rbjk/weixin/getDeviceCodeData/'+app.globalData.deviceId,
            data:{},
            method:'GET',
            header:{
              token:app.globalData.token
            },
            success:function(res){
              console.log("统计===============圆环",res)
              option.series[0].data[0].value = res.data.t0
              option.series[0].data[1].value = res.data.t1
              option.series[0].data[2].value = res.data.t2
              option.series[0].data[3].value = res.data.t3
              option.series[0].data[4].value = res.data.t4
              chart.setOption(option);
    
            }
          })


        }
      }
    })
  
    return chart;
}

Page({
  data: {
      winWidth: 0,
      winHeight: 0,
      currentTab: "0",
      ec: {
        onInit: initChart
      },
      timeData:null,
      limit:0,
      timer:0,
      lockReconnect:false,
      sockTimer:0,
      heartRate:0,
      breathRate:0,
      heartRate1:0,
      index: 0,
      array:['美国','中国','巴西','日本'],
      index2: 0,
      array2:['美国','中国','巴西','日本'],

      dateTime:null,
      dateTimeArray: null,

      dateTime1:null,
      dateTimeArray1:null,

      startYear: 2000,
      endYear: 2050,

      startTimer:null,
      endTimer:null
  },

  onReady: function () {
    
  },


  onLoad: function() {
      var that = this;
      //获取当前设备的宽高
      wx.getSystemInfo({
          success: function( res ) {
              that.setData( {
                  winWidth: res.windowWidth,
                  winHeight: res.windowHeight
              });
          }
      });

      // 获取完整的年月日 时分秒，以及默认显示的数组
      var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
      var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);

      this.setData({
        dateTime:obj.dateTime,
        dateTimeArray: obj.dateTimeArray,
        dateTimeArray1: obj1.dateTimeArray,
        dateTime1: obj1.dateTime
      })

  },
    
  //  tab切换逻辑
  swichNav: function( e ) {
      var that = this;
      // console.log("点击。。。。",e.currentTarget.dataset.current)
      if(e.currentTarget.dataset.current == '1'){
          that.selectComponent("#monitor").init();
          app.globalData.iscanvas = true;

          // 请求监测接口设备
          if(app.globalData.ismonitor){
            // app.globalData.ismonitor = false;
            console.log("监测=====",app.globalData.ismonitor,"token..........",app.globalData.token)
            
            if(app.globalData.token){
              //请求设备编号
              wx.request({
                url: 'https://www.renbojiaoyu.cn/rbjk/weixin/getUserDeviceCode',
                data:{},
                method:'GET',
                header:{
                  token:app.globalData.token
                },
                success:function(res){
                  console.log("设备编号===========",res)
                  if(res.data.code == 500){
                    wx.showModal({
                      title:'提示',
                      content:res.data.msg+'请绑定设备',
                      showCancel:false,
                      success(r){
                        if(r.confirm){
                          // 确定
                          that.selectComponent("#monitor").clear();
                          that.closeSocket();
                          that.setData({
                              currentTab: "0"
                          })

                        }else if(r.cancel){
                          // 取消
                        }
                      }
                    })
                  }else if(res.data.code == 0){
                    app.globalData.deviceId = res.data.deviceCode;
                    app.globalData.socketMsgQueue = res.data.deviceCode;
                    if (app.globalData.socketStatus === 'closed') {
                      that.openSocket();
                    }
                  }
                }
              })
            }

          }else{
            // http://192.168.10.211:8080/renren-fast/weixin/bindDevice/8967907654975797100554848484857
            // 发送监听设备数据消息 websock 已经触发检测，点击切换
            console.log("切换========")
            that.openSocket();
            // if (app.globalData.socketStatus === 'closed') {
            //   that.openSocket();
            // }
          }

      }else{
          if(app.globalData.iscanvas){
              that.selectComponent("#monitor").clear();
              that.closeSocket();
          }
          if(e.currentTarget.dataset.current == '2'){
            that.getCountDeviceId();
          }
      }


      if( this.data.currentTab === e.currentTarget.dataset.current ) {
          return false;
      } else {
          that.setData({
              currentTab: e.currentTarget.dataset.current
          })
      }

  },

  bindChange: function( e ) {
      var that = this;
      that.setData( { currentTab: e.detail.current });
  },


  // 打开socket信道
  openSocket() {
    // 注意：通过 WebSocket 连接发送数据。需要先 wx.connectSocket，并在 wx.onSocketOpen 回调之后才能发送。
    // 创建一个 WebSocket 连接
      wx.connectSocket({
        url: 'wss://wss.renbojiaoyu.cn', // 如果使用http协议，url的开头应该是'ws'，是https协议 wss
      })

      // 打开时的动作
      wx.onSocketOpen((res) => {
        console.log('WebSocket 已连接', res)
        app.globalData.socketStatus = 'connected'; // 标记打开
        clearInterval(app.globalData.sockTimer)
        app.globalData.sockTimer = setInterval(()=>{
          this.sendSocketMessage(app.globalData.socketMsgQueue)
        },1000)
      })

      // 监听 WebSocket 接受到服务器的消息事件
      wx.onSocketMessage(msg => {
        // console.log(msg.data)
        //把JSONStr转为JSON
        if (typeof msg.data !== 'object') {
          // msg.data = msg.data.replace(/\\"/g, "");
          var jj = JSON.parse(msg.data);
          msg.data = jj;
        }
        this.setData({
          heartRate:msg.data.heartRate,
          breathRate:msg.data.breathRate
        })

        app.globalData.breathRate = msg.data.breathRate;
        app.globalData.heartRate = msg.data.heartRate;

        console.log("【websocket 监听到消息】内容如下：",msg.data.heartRate,msg.data.breathRate);
      });

      // 断开时的动作
      wx.onSocketClose((res) => {
        console.log('WebSocket 已断开' , res)
        clearInterval(app.globalData.sockTimer);
        this.reconnect();
        // this.closeSocket()
        // app.globalData.socketStatus = 'closed'
      })

      // 报错时的动作
      wx.onSocketError(error => {
        console.error('socket error:', error)
        clearInterval(app.globalData.sockTimer);
        this.reconnect()
      })
  },

  // 关闭信道
  closeSocket() {
    // 注意这里有时序问题，
    // 如果 wx.connectSocket 还没回调 wx.onSocketOpen，而先调用 wx.closeSocket，那么就做不到关闭 WebSocket 的目的。
    // 必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。
    if (app.globalData.socketStatus === 'connected') {
      clearInterval(app.globalData.sockTimer);
      // 关闭 WebSocket 连接
      wx.closeSocket({
        success: (res) => {
          console.log("关闭 WebSocket 连接" , res);
          app.globalData.socketStatus = 'closed';
          
        }
      })
    }
  },

  //发送消息函数
  sendSocketMessage(msg) {
    if (app.globalData.socketStatus === 'connected') {
      // 自定义的发给后台识别的参数 ，我这里发送的是数组里面的内容 
      wx.sendSocketMessage({
        data: msg
      })
    } else {
      app.globalData.socketMsgQueue = msg
    }
  },

  //断线重连接
  reconnect(){
    clearInterval(app.globalData.sockTimer);

    if(this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer);
    if(this.data.limit < 3){
      this.timer = setTimeout(()=>{
        this.openSocket();
        this.lockReconnect = false;
      },5000)
      this.setData({
        limit:this.data.limit + 1
      })
    }
  },

  //统计----请求设备编号
  getCountDeviceId(){
    let that = this;
    //请求设备编号
    if(app.globalData.token && app.globalData.deviceId == null){
      wx.request({
        url: 'https://www.renbojiaoyu.cn/rbjk/weixin/getUserDeviceCode',
        data:{},
        method:'GET',
        header:{
          token:app.globalData.token
        },
        success:function(res){
          console.log("统计设备编号===========",res)
          if(res.data.code == 500){
            wx.showModal({
              title:'提示',
              content:res.data.msg+'请绑定设备',
              showCancel:false,
              success(r){
                if(r.confirm){
                  // 确定
                  // that.selectComponent("#monitor").clear();
                  that.setData({
                      currentTab: "0"
                  })
  
                }else if(r.cancel){
                  // 取消
                }
              }
            })
          }else if(res.data.code == 0){
            app.globalData.deviceId = res.data.deviceCode;
          }
        }
      })
    }
  },

  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  bindPickerChange2: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },

  changeDateTime(e){
    this.setData({ dateTime: e.detail.value });
  },

  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },

  changeDateTimeColumn(e){
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr
    });

    this.data.startTimer = this.getFormate(this.data.dateTime);
    console.log("开始。。。。",this.data.startTimer,this.data.dateTime1);
    
  },

  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr
    });

    this.data.endTimer = this.getFormate(this.data.dateTime1);
    console.log("结束。。。。。",endTimer);
  },


  // 转变日期格式
  getFormate(arr){

    let year,month,day,timer,minter,second;
    year = '20' + arr[0];
    arr[1] = arr[1]+1;
    arr[2] = arr[2]+1;
    month = arr[1]<10 ? '0'+arr[1] : ''+arr[1];
    day = arr[2]<10 ? '0'+arr[2] : ''+arr[2];
    timer = arr[3]<10 ? '0'+arr[3] : ''+arr[3];
    minter = arr[4]<10 ? '0'+arr[4] : ''+arr[4];
    second = arr[5]<10 ? '0'+arr[5] : ''+arr[5];
    return year+'-'+month+'-'+day+' '+timer+':'+minter+':'+second;

  }

})